<template>
  <div>
    <div style="display: flex;justify-content: space-between;">
      <div style="width: 20%;">
        <el-form
          :model="formInfo"
          label-position="left"
          label-width="100px"
        >
          <el-form-item label="学生姓名" prop="name">
            <el-input v-model="formInfo.name" type="text" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="学生照片" prop="janitor_name">
            <el-upload
              class="avatar-uploader"
              action="https://up-z1.qiniup.com"
              :data="uploadData"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="formInfo.img" :src="formInfo.img" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="家庭住址" prop="janitor_name">
            <el-input v-model="formInfo.address" type="text" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="所在学部" prop="name">
            <el-cascader
              v-model="formInfo.select_class"
              clearable
              :options="selectClassList"
              @change="handleGetInfoByList"
            />
          </el-form-item>
          <el-form-item label="学号" prop="janitor_name">
            <span>{{ formInfo.s_no }}</span>
          </el-form-item>
          <el-form-item label="邀请码" prop="janitor_name">
            <span>{{ formInfo.invite_code }}</span>
          </el-form-item>
        </el-form>
      </div>
      <div class="parent" style="width: 70%">
        <div>
          <span class="parent-name">家长姓名</span>
          <el-button plain @click="handleIsAdd('create')">添加</el-button>
        </div>
        <div style="display: flex;flex-wrap: wrap;">
          <div v-for="(item , index) of formInfo.parents" :key="index" class="parent-box" @click="handleIsAdd('edit',index)">
            <div class="parent-avatar">
              <img :src="item.img" alt="">
            </div>
            <div class="parent-info">
              <div class="parent-font">
                <span>{{ item.name }}</span>
                <span>{{ item.relationship }}</span>
              </div>
              <div class="parent-phone">
                <span>{{ item.tel_num }}</span>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
    <div style="margin: 5% 0 0 5%;">
      <el-button plain style="margin-right: 3%;" @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="handleChangeStudentInfo">保存</el-button>
    </div>
    <wx-dialog
      ref="myDialog"
      :visible.sync="editJanitor"
      :title="isType"
      width="500px"
      @ok="handleAddParInfo()"
    >
      <div>
        <el-form
          label-position="left"
          label-width="100px"
        >
          <el-form-item label="与学生关系" prop="relationship">
            <el-select
              v-if="addParentsList.parents !== null"
              v-model="addParentsList.relationship"
              style="width: 100%;"
              clearable
              placeholder="请选择班级"
            >
              <el-option
                v-for="(item,index) of PARENTLIST"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="家长姓名" prop="name">
            <el-input v-model="addParentsList.name" type="text" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="家长手机号" prop="tel_num">
            <el-input v-model="addParentsList.tel_num" type="number" maxlength="11" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="家长照片" prop="img">
            <el-upload
              class="avatar-uploader"
              action="https://up-z1.qiniup.com"
              :data="uploadData"
              :show-file-list="false"
              :before-upload="beforeAddAvatarUpload"
            >
              <img v-if="addParentsList.img" :src="addParentsList.img" class="avatar">
              <i v-if="!addParentsList.img" class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
    </wx-dialog>
  </div>
</template>

<script>
import WxDialog from '@/components/WxDialog'
import { PARENTLIST } from '@/views/constants'
import { get, post } from '@/utils/request'
import uploadNormalFile from '@/api/QiuNiu'

export default {
  name: 'StudentDetail',
  components: {
    WxDialog
  },
  props: {
    formInfo: {
      type: Object
    }
  },
  data() {
    return {
      qiNiuToken: '',
      uploadData: {
        token: '',
        key: ''
      },
      parentIndex: 0,
      editIsAdd: '',
      isType: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      selectClassList: [],
      addParentsList: {
        relationship: '',
        name: '',
        tel_num: '',
        img: ''
      },
      imageUrl: '',
      parentsIndex: 0,
      PARENTLIST,
      baseApi: 'api/adminPortal/student/',
      editJanitor: false,
      select_dept: []
    }
  },
  watch: {
    formInfo() {
      this.formInfo.year_department_id = this.formInfo.department.id
      this.formInfo.grade_name = this.formInfo.grade.name
      this.formInfo.class_name = this.formInfo.class.name
      this.formInfo.select_class = [this.formInfo.department.id, this.formInfo.grade.name, this.formInfo.class.name]
    }
  },
  mounted() {
    this.handleGetYearDepartment()
    this.handleGetDepartmentList()
    this.handleGetQiNiu()
  },
  methods: {
    handleGetQiNiu() {
      post('api/userPortal/accountUser/getQiniuUploadToken').then(res => {
        this.uploadData.token = res.data
      })
    },
    handleIsAdd(type, index) {
      this.editIsAdd = type
      this.parentIndex = index
      if (type === 'create') {
        this.isType = '添加'
        this.addParentsList = {}
      }
      if (type === 'edit') {
        this.isType = '编辑'
        this.addParentsList = JSON.parse(JSON.stringify(this.formInfo.parents[index]))
      }
      this.editJanitor = true
    },
    beforeAvatarUpload(file) {
      uploadNormalFile(file, (res) => {
        this.formInfo.img = res
      })
    },
    beforeAddAvatarUpload(file) {
      uploadNormalFile(file, (res) => {
        this.$set(this.addParentsList, 'img', res)
      })
    },
    handleRemove(file) {
      console.log(file)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleGetInfoByList(data) {
      console.log(data)
      this.formInfo.year_department_id = data[0]
      this.formInfo.grade_name = data[1]
      this.formInfo.class_name = data[2]
    },
    handleGetDepartmentList() {
      get('api/adminPortal/yearDepartment/getListByCon', {
        level: 'class'
      }).then((res) => {
        res.data.data.forEach((item) => {
          const onelist = {
            label: item.name,
            value: item.id,
            children: []
          }
          this.selectClassList.push(onelist)
          item.grade_arr.forEach((its) => {
            const twoList = {
              value: its.name,
              label: `${its.name}年级`,
              children: []
            }
            onelist.children.push(twoList)
            its.class_arr.forEach((index) => {
              const threeList = {
                label: `${index.name}班`,
                value: index.name
              }
              twoList.children.push(threeList)
            })
          })
          return onelist
        })
      })
    },
    handleAddParInfo() {
      if (this.addParentsList.relationship === undefined) {
        this.$message.error('请选择关系')
        return
      }
      if (this.addParentsList.img === undefined) {
        this.$message.error('请上传头像')
        return
      }
      if (this.addParentsList.tel_num === undefined) {
        this.$message.error('请填写手机号')
        return
      }
      if (this.addParentsList.name === undefined) {
        this.$message.error('请填写姓名')
        return
      }
      const infoList = ['name', 'relationship', 'img', 'tel_num']
      const url = `api/adminPortal/parent/${this.editIsAdd}`
      this.addParentsList.student_id = this.formInfo.id
      post(url, this.addParentsList).then((res) => {
        if (res.code === 200) {
          this.$message(`${this.isType}成功`)
          if (this.editIsAdd === 'edit') {
            infoList.forEach((item) => {
              this.$set(this.formInfo.parents[this.parentIndex], item, this.addParentsList[item])
            })
          }
          if (this.editIsAdd === 'create') {
            // TODO... 查详细的接口给他贴进去
            get('api/adminPortal/student/getById', {
              level: 'parent',
              id: this.formInfo.id
            }).then((res) => {
              this.formInfo.parents = res.data.parents
            })
          }
          this.editJanitor = false
          return
        }
        this.$message(res.msg)
      })
    },
    handleChangeStudentInfo() {
      const array = ['id', 'name', 'address', 'img']
      const list = {}
      for (let i = 0; i < 6; i++) {
        list[array[i]] = this.formInfo[array[i]]
      }
      list.class_name = this.formInfo.class_name
      list.school_id = 1
      list.department_id = this.formInfo.year_department_id
      list.grade_name = this.formInfo.grade_name
      if (list.name === '') {
        this.$message.error('请填写姓名')
        return
      }
      if (list.img === '') {
        this.$message.error('请选择头像')
        return
      }
      if (list.address === '') {
        this.$message.error('请选择家庭住址')
        return
      }
      if (list.class_name === '') {
        this.$message.error('请选择班级')
        return
      }
      post('api/adminPortal/student/edit', list).then((res) => {
        if (res.code) {
          this.formInfo = res.data
          this.$message('修改成功')
          location.reload()
          return
        }
        this.$message(res.msg)
      })
    },
    handleChangeParents(index) {
      this.parentsIndex = index
      this.editJanitor = true
    },
    handleGetYearDepartment() {
      get('api/adminPortal/yearDepartment/getListByCon?level=year_grade').then((res) => {
        this.select_dept = res.data.data.map((item) => {
          const list = {
            type: item.id,
            label: item.name
          }
          return list
        })
      })
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style lang="scss" src="./style/Form.scss" scoped>

</style>
